package com.gqb.lucene.PageQuery;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;


public class Indexer {
	private String indexDir;
	private IndexWriter writer;
	private static Indexer indexer;
	private Searcher searcher;
	public Indexer(String indexDir) throws IOException {
		super();
		this.indexDir = indexDir;
		File file=new File(indexDir);
		if(!file.exists())
			file.mkdirs();
		Directory directory=FSDirectory.open(Paths.get(indexDir));
		SmartChineseAnalyzer analyzer=new SmartChineseAnalyzer();
		IndexWriterConfig iwc=new IndexWriterConfig(analyzer);
		iwc.setMaxBufferedDocs(100);
		searcher=new Searcher(indexDir);
		this.writer=new IndexWriter(directory, iwc);
	}
	
	public synchronized static Indexer getInstance(String indexDir) throws IOException{
		if(null==indexer){
			indexer=new Indexer(indexDir);
			return indexer;
		}else {
			return indexer;
		}
	}
	
	public void  close() throws IOException {
//		writer.close();
	}
	
	public void index(Document document) throws IOException{
		writer.addDocument(document);
		
		writer.commit();
	}
	
	public void update(String id,String field,String value) throws IOException{
		TopDocs topDocs= searcher.TermQueryL("id", id);
		ScoreDoc[] scoreDocs=topDocs.scoreDocs;
		if(scoreDocs.length>0){
			Document oldDocument=searcher.getDocument(scoreDocs[0]);
			oldDocument.removeField(field);
			writer.updateDocument(new Term("id", id), oldDocument);
			writer.commit();
			searcher.reopen(writer);
			Document newDocument=searcher.getDocument(scoreDocs[0]);
			newDocument.add(new StringField("lwdw",value, Field.Store.YES));
			writer.updateDocument(new Term("id", id), newDocument);
			writer.commit();
		}
	}
}
